import 'dart:async';
import 'dart:convert';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/building_index/building_index_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/building_index/refresh_building_index_terminal_settings_event.dart';
import 'package:e_reception_flutter/ui/building_index/refresh_diy_page_event.dart';
import 'package:e_reception_flutter/utils/file_utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_save_util_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'building_index_change_module_page.dart';
import 'building_index_diy_floor_settings_page.dart';
import 'building_index_diy_list_response_bean.dart';
import 'building_index_select_terminal_page.dart';
import 'building_index_terminal_list_response_bean.dart';
import 'building_index_view_model.dart';

///楼层指引diy详情
class BuildingIndexDiyDetailPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "BuildingIndexDiyDetailPage";
  final BuildingIndexDiyBean itemInfo;
  //标志是否是新创建的来的，用来判断是否要更新截图
  final bool newCreate;
  const BuildingIndexDiyDetailPage(
      {Key key, this.itemInfo, this.newCreate}) : super(key:key);

  @override
  State<StatefulWidget> createState() =>_BuildingIndexDiyDetailPageState();

  static Future<dynamic> navigatorPush(BuildContext context,
      BuildingIndexDiyBean itemInfo, bool newCreate){
    return RouterUtils.routeForFutureResult(
        context,
        BuildingIndexDiyDetailPage(
          itemInfo:itemInfo,
          newCreate:newCreate,
        ),
        routeName: BuildingIndexDiyDetailPage.ROUTER
    );
  }

}

class _BuildingIndexDiyDetailPageState extends BaseState<BuildingIndexDiyDetailPage>{
  BuildingIndexViewModel _viewModel;
  WebViewController _webViewController;
  //webview加载成功
  bool isUrlLoadComplete = false;
  BuildingIndexDiyBean _itemInfo;
  String _loadUrl;
  String _picUrl;
  int _diyCount = 0;
  ComWbrandBean _detailInfo;
  List<HsnListBean> _terminalList;
  StreamSubscription _terminalSettingsStreamSubscription;
  StreamSubscription _diyDetailStreamSubscription;
  //标志是否需要更新diy图片
  bool _needUpdatePic = false;
  @override
  void initState() {
    super.initState();
    _itemInfo = widget?.itemInfo;
    _terminalList = new List();
    String cacheKey = NetApi.BUILDING_INDEX_DETAIL + (UserRepository.getInstance().authId?? "")
        + _itemInfo?.id;
    _viewModel = BuildingIndexViewModel(this);
    _viewModel.getBuildingDetailOnLine(_itemInfo?.id, cacheKey, null);
    _viewModel.getTerminalList("");
    _terminalSettingsStreamSubscription =
        VgEventBus.global.on<RefreshBuildingIndexTerminalSettingsEvent>()?.listen((event) {
          _viewModel.getTerminalList("");
        });
    _diyDetailStreamSubscription =
        VgEventBus.global.on<RefreshDiyPageEvent>()?.listen((event) {
          if(event.isDelete??false){
            print("指示牌删除了，不更新");
            return;
          }
          //海报详情数据更新了
          _viewModel.getBuildingDetailOnLine(_itemInfo?.id, cacheKey, null);
          _needUpdatePic = true;
        });
    _needUpdatePic = (widget?.newCreate??false);

  }

  @override
  void dispose() {
    super.dispose();
    _terminalSettingsStreamSubscription.cancel();
    _diyDetailStreamSubscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
      child: WillPopScope(
        onWillPop: _withdrawFront,
        child: Scaffold(
          backgroundColor: Colors.white,
          resizeToAvoidBottomPadding: false,
          resizeToAvoidBottomInset: false,
          body: _toPlaceHolderWidget(),
        ),
      ),
    );
  }

  void onBackPressed(){
    if(!(_needUpdatePic??false)){
      //不需要更新，直接返回
      RouterUtils.pop(context);
      return;
    }
    loading(true, msg: "合成中");
    _webViewController?.evaluateJavascript("download_img()");
    Future.delayed(Duration(seconds: 5), () {
      if (mounted) return;
      loading(false);
    });

  }

  Future<bool> _withdrawFront() async {
    if(!(_needUpdatePic??false)){
      //不需要更新，直接返回
      return true;
    }
    loading(true, msg: "合成中");
    _webViewController?.evaluateJavascript("download_img()");
    Future.delayed(Duration(seconds: 5), () {
      if (mounted) return;
      loading(false);
    });
  }


  Widget _toPlaceHolderWidget() {
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: value == PlaceHolderStatusType.loading,
            errorStatus: value == PlaceHolderStatusType.error,
            emptyCustomWidget: _defaultEmptyCustomWidget("暂无内容"),
            errorCustomWidget: _defaultEmptyCustomWidget("网络断线 重新获取"),
            errorOnClick: () => _viewModel
                .getBuildingIndexDetail(_itemInfo?.id),
            loadingOnClick: () => _viewModel
                .getBuildingIndexDetail(_itemInfo?.id),
            child: child,
          );
        },
        child: _toInfoWidget());
  }

  Widget _defaultEmptyCustomWidget(String msg) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Image.asset(
          "images/icon_empty_white.png",
          width: 120,
          gaplessPlayback: true,
        ),
        SizedBox(
          height: 8,
        ),
        Text(
          msg??"暂无内容",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 13,
          ),
        )
      ],
    );
  }


  Widget _toInfoWidget(){
    return ValueListenableBuilder(
      valueListenable: _viewModel?.buildingIndexDetailValueNotifier,
      builder: (BuildContext context, BuildingIndexDetailBean detailBean, Widget child){
        if(detailBean != null && detailBean.comWbrand != null){
          _detailInfo = detailBean?.comWbrand;
          _loadUrl = _detailInfo?.htmlurl;
          _picUrl = _detailInfo?.picurl;
          //containerFlg 00大屏机 01app
          _loadUrl = _loadUrl + "?containerFlg=01&contJson=" + Uri.encodeComponent(json.encode(detailBean));
          //第一次进入的时候，调用loadurl会导致海报加载两次，会闪，所以加个判断
          //_needUpdatePic是用来标记海报是否需要重新截图的，也可以用作海报是否有变化的标记，所以初次加载海报是没有变化的。
          //所以只有当_needUpdatePic为true时，才主动执行loadurl
          if(_webViewController != null && (_needUpdatePic??false)){
            _webViewController.loadUrl(_loadUrl);
          }
        }else{
          // _loadUrl = _itemInfo?.htmlurl;
          // _picUrl = _itemInfo?.picurl;
        }
        return Stack(
          children: [
            Column(
                children:[
                  _toTopBarWidget(),
                  SizedBox(height: 10,),
                  _toWebViewWidget(),
                ]),
            _toBottomWidget(),
          ],
        );
      },
    );
  }

  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "详情",
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: _toTerminalWidget(),
      navFunction: onBackPressed,
    );
  }

  Widget _toTerminalWidget(){
    return ValueListenableBuilder(
      valueListenable: _viewModel?.buildingIndexTerminalValueNotifier,
      builder: (BuildContext context, BuildingIndexTerminalDataBean terminalDataBean, Widget child){
        String hsns = "";
        if(terminalDataBean != null && terminalDataBean.hsnList.isNotEmpty){
          _terminalList.clear();
          _terminalList.addAll(terminalDataBean.hsnList);
          _diyCount = 0;
          _terminalList.forEach((element) {
            if(_itemInfo?.id == element.comwid){
              _diyCount++;
              hsns += element.hsn;
              hsns += ",";
            }
          });
        }
        if(StringUtils.isNotEmpty(hsns)){
          hsns = hsns.substring(0, hsns.length-1);
        }
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: ()async{
            // if(_diyCount < 1){
            //   return;
            // }
            if(_terminalList.isEmpty){
              VgToastUtils.toast(context, "暂无可投放终端");
              return;
            }
            // BuildingIndexSetTerminalPage.navigatorPush(context, _itemInfo?.id,
            //     _picUrl, _terminalList, hsns);

            BuildingIndexSelectTerminalPage.navigatorPush(context,
                _itemInfo?.id, hsns, _terminalList);
          },
          child: Container(
            height: 24,
            alignment: Alignment.center,
            padding: EdgeInsets.symmetric(horizontal: 12),
            decoration: BoxDecoration(
                color: (_diyCount > 0)
                    ? ThemeRepository.getInstance().getHintGreenColor_00C6C4()
                    : ThemeRepository.getInstance().getMinorRedColor_F95355(),
                borderRadius: BorderRadius.circular(12)
            ),
            child: Text(
              "播放终端·${_diyCount??0}",
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  fontWeight: FontWeight.w600
              ),
            ),
          ),

        );
      },
    );

  }

  Widget _toBottomWidget(){
    double bottomH = ScreenUtils.getBottomBarH(context);
    return Align(
      alignment: Alignment.bottomCenter,
      child: Container(
        height: 60 + bottomH,
        color: Colors.white,
        alignment: Alignment.center,
        padding: EdgeInsets.only(left: 15, right: 15, bottom: bottomH),
        child: Row(
          children: [
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () async{
                if(_diyCount > 0){
                  bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
                    title: "提示",
                    content: "显示屏端的楼层指示牌也将同步删除，确定继续？",
                    cancelText: "取消",
                    confirmText: "删除",
                    confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                    cancelBgColor: Color(0xFFF6F7F9),
                    titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    widgetBgColor: Colors.white,
                  );
                  if (result ?? false) {
                    _viewModel.deleteBuildingIndex(context, _detailInfo?.id);
                  }
                }else{
                  bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
                    title: "提示",
                    content: "删除后不可恢复，确定删除该楼层指示牌？",
                    cancelText: "取消",
                    confirmText: "删除",
                    confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                    cancelBgColor: Color(0xFFF6F7F9),
                    titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
                    widgetBgColor: Colors.white,
                  );
                  if (result ?? false) {
                    _viewModel.deleteBuildingIndex(context, _detailInfo?.id);
                  }
                }
              },
              child: ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Container(
                  width: 70,
                  height: 40,
                  alignment: Alignment.center,
                  color: ThemeRepository.getInstance().getTextColor_D0E0F7(),
                  child: Text(
                    "删除",
                    style: TextStyle(
                        color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                        fontSize: 15
                    ),
                  ),
                ),
              ),
            ),
            SizedBox(width: 8,),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: ()async{
                bool success = await BuildingIndexChangeModelPage.navigatorPush(context, _detailInfo.id, _detailInfo.syswid);
                if(success??false){
                  _viewModel.getBuildingIndexDetail(_itemInfo?.id);
                }
              },
              child: ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Container(
                  height: 40,
                  width: (ScreenUtils.screenW(context) - 30 - 70 - 16)/2,
                  alignment: Alignment.center,
                  color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                  child: Text(
                    "更换模板",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 15
                    ),
                  ),
                ),
              ),
            ),
            SizedBox(width: 8,),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: (){
                //来源 00我制作的详情，模板制作01
                BuildingIndexDiyFloorSettingsPage.navigatorPush(context, _detailInfo?.id, "00");
              },
              child: ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Container(
                  height: 40,
                  width: (ScreenUtils.screenW(context) - 30 - 70 - 16)/2,
                  alignment: Alignment.center,
                  color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                  child: Text(
                    "修改内容",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 15
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _toWebViewWidget() {
    double maxHeight = ScreenUtils.screenH(context)
        - ScreenUtils.getStatusBarH(context)
        - 44
        - 10
        - 60
        - ScreenUtils.getBottomBarH(context);

    double screenWidth = ScreenUtils.screenW(context) - 30;
    double width;
    double height;
    if (maxHeight / screenWidth <= 16 / 9) {
      width = maxHeight / (16 / 9);
      height = maxHeight;
    } else {
      width = screenWidth;
      height = screenWidth * (16 / 9);
    }
    print("屏幕宽： ${screenWidth}");
    print("屏幕高： ${maxHeight}");
    print("真实宽： ${width}");
    print("真实高： ${height}");
    print("url:$_loadUrl");
    return Container(
      color: Colors.white,
      height: height,
      width: width,
      child: ClipRRect(
        borderRadius: BorderRadius.only(topLeft: Radius.circular(8), topRight: Radius.circular(8)),
        child: Stack(
          children: [
            Opacity(
              opacity: isUrlLoadComplete ? 1 : 0,
              child: WebView(
                initialUrl: _loadUrl,
                javascriptMode: JavascriptMode.unrestricted,
                javascriptChannels: <JavascriptChannel>[
                  _downloadJavascriptChannel(context),
                ].toSet(),
                onPageFinished: (String url) {
                  print("加载完成\n" + url);
                  if(!(isUrlLoadComplete??false)){
                    setState(() {
                      isUrlLoadComplete = true;
                    });
                  }
                },
                onWebViewCreated: (controller) {
                  _webViewController = controller;
                },
                onWebResourceError: (error){
                  print("加载失败：" + error?.description??"");
                  String errorInfo = error?.description??"";
                  if(errorInfo.contains("net::ERR_INTERNET_DISCONNECTED")
                      || errorInfo.contains("404")
                      || errorInfo.contains("500")
                      || errorInfo.contains("Error")
                      || errorInfo.contains("找不到网页")
                      || errorInfo.contains("网页无法打开")){
                    _viewModel?.statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
                  }
                },
              ),
            ),
            Center(
              child: Visibility(
                visible: !isUrlLoadComplete,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    CircularProgressIndicator(
                      strokeWidth: 2,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      "正在加载",
                      style: TextStyle(
                          color: ThemeRepository.getInstance()
                              .getCardBgColor_21263C(),
                          fontSize: 10),
                    )
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  JavascriptChannel _downloadJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'downloadPoster',
        onMessageReceived: (JavascriptMessage message) async {
          if (StringUtils.isEmpty(message.message) || !message.message.contains(",")) {
            toast("下载失败，请重试");
            return;
          }
          String base64Str = message.message.split(",")[1];
          //下载
          // SaveUtils.saveImage(base64Url: base64Str);
          String imagePath =
          await FileUtils.createFileFromString(base64Str);
          if (StringUtils.isNotEmpty(imagePath)) {
            _viewModel.updateDiyBuildingIndexPicUrl(context, _itemInfo?.id, imagePath);
          }
        });
  }

}